<template>
    <div class="container">

        <!-- 基本搜索+功能按钮 -->
        <el-form ref="searchForm1" :inline="true" :model="searchForm" size="medium" label-width="70px">
            <div class="table_tool_bar_wrap">
                <div class="base_wrap mb10">
                    <div class="left">
                        <div>
                            <el-form-item label="订单状态" prop="status">
                                <el-radio-group v-model="searchForm.status" @change="handleChangeStatus" size="small">
                                    <el-radio-button label="">全部</el-radio-button>
                                    <el-radio-button :label="0">待付款</el-radio-button>
                                    <el-radio-button :label="1">待发货</el-radio-button>
                                    <el-radio-button :label="2">待收货</el-radio-button>
                                    <el-radio-button :label="3">已完成</el-radio-button>
                                    <el-radio-button :label="4">已关闭</el-radio-button>
                                </el-radio-group>
                            </el-form-item>

                        </div>
                    </div>
                </div>
                <div class="base_wrap mb10">
                    <div class="left">
                        <el-form-item label="时间选择" prop="dateAttr">
                            <el-radio-group v-model="searchForm.dateAttr" @change="handleChangeDateAttr" size="small">
                                <el-radio-button label="">全部</el-radio-button>
                                <el-radio-button :label="0">今天</el-radio-button>
                                <el-radio-button :label="1">昨天</el-radio-button>
                                <el-radio-button :label="2">最近7天</el-radio-button>
                                <el-radio-button :label="3">最近30天</el-radio-button>
                                <el-radio-button :label="4">本月</el-radio-button>
                                <el-radio-button :label="5">本年</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="">
                            <el-date-picker
                                size="small"
                                v-model="dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="yyyy-MM-dd"
                                clearable
                                style="width: 280px">
                            </el-date-picker>
                        </el-form-item>
                    </div>
                </div>
                <div class="base_wrap mb10">
                    <div class="left">
                        <el-form-item label="快捷搜索" prop="keyword">
                            <el-input placeholder="" v-model="searchForm.keyword" clearable size="small"/>
                        </el-form-item>
                        <el-button @click="handleSearch" type="primary" size="small">搜索</el-button>
                        <el-button @click="handleReset" type="info" plain size="small">重置</el-button>
                        <el-button @click="handleExport" type="primary" plain size="small">导出</el-button>
                        <!-- <el-button type="text" size="medium" @click="searchFlag = !searchFlag">
                            高级搜索<i class="el-icon--right" :class="searchFlag?'el-icon-arrow-down':'el-icon-arrow-up'"></i>
                        </el-button> -->
                    </div>
                </div>
            </div>
        </el-form>

        <!-- 高级搜索 -->
        <el-form class="mt10" ref="searchForm2" :inline="true" :model="searchForm" v-show="!searchFlag" size="medium" label-width="70px">
            <div class="table_tool_bar_wrap">
                <div class="base_wrap mb10">
                    <div class="left">
                        <el-form-item label="会员名称" prop="memberUsername">
                            <el-input placeholder="" v-model="searchForm.memberUsername" clearable size="small"/>
                        </el-form-item>
                        <el-form-item label="配送方式" prop="memberUsername">
                            <el-input placeholder="" v-model="searchForm.memberUsername" clearable size="small"/>
                        </el-form-item>

                        <el-form-item label="配送方式" prop="deliverType">
                            <el-select v-model="searchForm.deliverType" placeholder="请选择">
                                <el-option label="送货上门" :value="0" />
                                <el-option label="到店自提" :value="1" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </div>


        </el-form>

        <!-- 表格 -->
        <el-table
            ref="table"
            size="medium"
            height="500"
            empty-text="暂无数据"
            element-loading-text="给我一点时间"
            fit border highlight-current-row
            :stripe="stripe"
            v-loading="loading"
            :data="dataList"
            @selection-change="handleSelection">

            <el-table-column type="selection" width="55" prop="selection" v-if="isHideColumn('selection')" align="center"></el-table-column>
            <el-table-column label="订单信息" prop="orderInfo" v-if="isHideColumn('orderInfo')" align="left" width="260">
                <template slot-scope="scope">
                    <div class="wrap">
                        <div>订单编号:{{scope.row.orderSn}}</div>
                        <div>订单类型:{{scope.row.orderType | formatOrderType}}</div>
                        <div>下单时间:{{scope.row.ctime}}</div>
                        <div v-if="scope.row.isRefund === 1">申请退款:<span style="color:red">已申请</span></div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="会员信息" prop="memberUsername" v-if="isHideColumn('memberUsername')" align="left" width="120" show-overflow-tooltip/>
            <el-table-column label="商品信息" prop="goodsName" v-if="isHideColumn('goodsName')" align="left" min-width="450">
                <template slot-scope="scope">
                    <div class="skus_wrap" v-for="(item, index) in scope.row.skus" :key="index">
                        <div class="sku_img">
                            <el-image style="width: 60px; height: 60px" :src="item.skuPic" :preview-src-list="[item.skuPic]" fit="contain"></el-image>
                        </div>
                        <div class="sku_name">
                            {{item.skuName}}
                        </div>
                        <div class="sku_amount">
                            <span>￥{{item.skuPrice}}</span>
                            <span>X{{item.skuNum}}</span>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="订单金额" prop="orderAmount" v-if="isHideColumn('orderAmount')" align="left" width="160">
                <template slot-scope="scope">
                    <div class="wrap">
                        <div>订单金额:￥{{scope.row.totalAmount}}</div>
                        <div class="payAmount">应付金额:￥{{scope.row.payAmount}}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="商品数量" prop="skuNum" v-if="isHideColumn('skuNum')" align="center" width="90">
                <template slot-scope="scope">
                    <div class="wrap">
                        {{scope.row.totalCount}}件
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="订单状态" prop="status" v-if="isHideColumn('status')" align="center" width="100">
                <template slot-scope="scope">
                    <div v-if="scope.row.isRefund != 1">
                        <el-tag type="primary" size="small" v-if="scope.row.status === 0">{{scope.row.status | formatStatus}}</el-tag>
                        <el-tag type="primary" size="small" v-else-if="scope.row.status === 1">{{scope.row.status | formatStatus}}</el-tag>
                        <el-tag type="primary" size="small" v-else-if="scope.row.status === 2">{{scope.row.status | formatStatus}}</el-tag>
                        <el-tag type="success" size="small" v-else-if="scope.row.status === 3">{{scope.row.status | formatStatus}}</el-tag>
                        <el-tag type="info" size="small" v-else-if="scope.row.status === 4">{{scope.row.status | formatStatus}}</el-tag>
                        <el-tag type="danger" size="small" v-else>禁用</el-tag>
                    </div>
                    <div v-else style="color:red">申请退款</div>
                </template>
            </el-table-column>

            <el-table-column label="操作" prop="btn" width="200px" align="left" fixed="right">
                <template slot-scope="scope">

                    <template v-if="scope.row.status == 0">
                        <el-button @click="handleCancelOrder(scope.row)" type="text" size="small">取消</el-button>
                    </template>
                    <template v-if="scope.row.status == 1">
                        <el-button @click="handleInnerDeliveryVisible(scope.row)" type="text" size="small">发货</el-button>
                        <el-button @click="handleCancelOrder(scope.row)" type="text" size="small">取消</el-button>
                    </template>
                    <template v-if="scope.row.status == 2 && scope.row.isRefund != 1">
                        <el-button @click="handleConfirmReceivePack(scope.row)" type="text" size="small">确认收货</el-button>
                    </template>

                    <el-button @click="handleDetailVisible(scope.row.id)" type="text" size="small">详情</el-button>

                    <el-dropdown @command="handleCommand">
                        <span class="el-dropdown-link">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'remarks')">订单备注</el-dropdown-item>
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'logistics')">物流跟踪</el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.status == 0 || scope.row.status == 4" :command="beforeHandleCommand(scope.$index, scope.row, 'deleted')">删除订单</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>

        </el-table>

        <!-- 分页 -->
        <TablePagination
            :total.sync="total"
            :page.sync="searchForm.page"
            :limit.sync="searchForm.limit"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"/>

        <!-- 订单详情 -->
        <Detail ref="detail" @refreshDataList="getDataList"></Detail>

        <!-- 物流跟踪 -->
        <Logistics ref="logistics" v-model="logistics.dialogVisible"></Logistics>

        <!-- 订单备注 -->
        <el-dialog
            width="30%"
            title="订单备注"
            :visible.sync="remarksOrder.dialogVisible">

                <el-input
                    type="textarea"
                    :rows="5"
                    placeholder="请输入内容"
                    clearable
                    v-model="remarksOrder.remarks">
                </el-input>

            <div slot="footer" class="dialog-footer">
                <el-button @click="remarksOrder.dialogVisible = false">关 闭</el-button>
                <el-button @click="handleRemarks" type="primary" :submitLoading="submitLoading">提 交</el-button>
            </div>
        </el-dialog>

        <!-- 订单发货 -->
        <el-dialog
            width="60%"
            title="订单发货"
            :visible.sync="deliveryOrder.dialogVisible">

            <div class="divider">
                <i class="el-icon-collection-tag"></i>
                <span class="title">收货信息</span>
            </div>
            <div class="detail_wrap">
                <div class="table_layout">
                    <el-row>
                        <el-col :span="4" class="table_cell_title">收件人</el-col>
                        <el-col :span="4" class="table_cell_title">手机号</el-col>
                        <el-col :span="4" class="table_cell_title">地址编码</el-col>
                        <el-col :span="12" class="table_cell_title">收件地址</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4" class="table_cell">{{order.receiverName}}</el-col>
                        <el-col :span="4" class="table_cell">{{order.receiverPhone}}</el-col>
                        <el-col :span="4" class="table_cell">{{order.receiverPostCode}}</el-col>
                        <el-col :span="12" class="table_cell">
                            {{order.receiverProvince}}
                            {{order.receiverCity}}
                            {{order.receiverRegion}}
                            {{order.receiverDetailAddress}}
                        </el-col>
                    </el-row>
                </div>
            </div>

            <div class="divider">
                <i class="el-icon-collection-tag"></i>
                <span class="title">快递配送</span>
            </div>
            <el-form ref="deliveryOrder" :model="deliveryOrder" :rules="rulesDelivery" @keyup.enter.native="handleExpressDelivery" label-width="120px">
                <el-form-item label="配送方式" prop="deliverType">
                    <el-radio-group v-model="deliveryOrder.deliverType">
                        <el-radio :label="0">送货上门</el-radio>
                        <el-radio :label="1">到店自提（无需快递）</el-radio>
                    </el-radio-group>
                </el-form-item>
                <div v-if="deliveryOrder.deliverType == 0">
                    <el-form-item label="选择快递">
                        <el-select placeholder="请选择物流公司" v-model="deliveryOrder.deliveryCompany" style="width: 300px">
                            <el-option
                                v-for="item in companyOptions"
                                :key="item.id"
                                :label="item.freightName"
                                :value="item.freightName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="快递单号" prop="deliverySn">
                        <el-input placeholder="" v-model="deliveryOrder.deliverySn" clearable style="width: 300px"></el-input>
                    </el-form-item>
                </div>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="deliveryOrder.dialogVisible = false">关 闭</el-button>
                <el-button @click="handleExpressDelivery" type="primary" :submitLoading="submitLoading">提 交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import TableMixin from '@/mixin/TableMixin'
import TablePagination from '@/views/components/table/table-pagination'
import Detail from './detail'
import Logistics from './logistics'
import { mapGetters } from 'vuex'
export default {
    mixins: [TableMixin],
    components: {
        TablePagination,
        Detail,
        Logistics
    },

    computed: {
        ...mapGetters(['user'])
    },

    data() {
        return {
            dataList: [],
            total: 0,
            loading: false,
            selectionRows: [],
            searchFlag: true,
            searchForm: {
                page: 1,
                limit: 10,
                sortColumns: 'ctime',
                sortType: 'desc',
                keyword: null,
                memberId: null,
                memberUsername: null,
                couponId: null,
                totalAmount: null,
                payAmount: null,
                freightAmount: null,
                promotionAmount: null,
                integrationAmount: null,
                couponAmount: null,
                discountAmount: null,
                orderType: null,
                payType: null,
                sourceType: null,
                status: '',
                dateAttr: '',
                dateRange: null,
            },
            dateRange: null,

            submitLoading: false,

            // 订单备注
            remarksOrder: {
                dialogVisible: false,
                id: null,
                remarks: null
            },

            // 物流跟踪
            logistics: {
                dialogVisible: false
            },

            // 物流公司
            companyOptions: [],

            // 订单信息
            order: {},

            // 订单发货
            deliveryOrder:{
                dialogVisible:false,
                id: null,
                deliverType: 0,
                deliveryCompany: null,
                deliverySn: null,
            },
            rulesDelivery: {
                deliverySn: [
                    { required: true, message: '快递单号不能为空', trigger: 'blur' }
                ]
            }
        }
    },

    created() {
    },

    mounted() {
        this.$nextTick(() => {
            this.getDataList()
        })
    },

    methods: {

        /**
         * 订单详情
         */
        handleDetailVisible(id) {
            this.$nextTick(() => {
                this.$refs.detail.init(id)
            })
        },

        /**
         * 删除
         */
        async handleDelete(row) {
            let ids = []
            if (row) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {
                const confirm = await this.$confirm('确定要删除？', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: '/mall/omsorder/delete',
                        method: 'POST',
                        data: ids
                    })
                    if (this.ResultMessage(res)) {
                        this.getDataList()
                    }
                }
            }
        },

        /**
         * 获取表格数据
         */
        async getDataList() {

            if(this.user.superAdmin === 1) { // 超级管理员

            } else if(this.user.type === 1) { // 系统用户

            } else if(this.user.type === 2) { // 代理商用户
                if(this.user.agentId) {
                    this.searchForm.agentId = this.user.agentId
                }
            }

            if(this.dateRange && this.dateRange.length > 0) {
                this.searchForm.dateAttr = ''
                this.searchForm.dateRange = this.dateRange.join(',')
            } else {
                this.searchForm.dateRange = null
            }

            this.loading = true
            const res = await this.$http({
                url: '/mall/omsorder/page',
                method: 'GET',
                params: this.searchForm
            })
            if (this.ResultMessage(res, false)) {
                this.dataList = res.data.records || []
                this.total = res.data.total
            }
            this.loading = false
        },

        /**
         * 取消订单
         */
        async handleCancelOrder(row) {
            const confirm = await this.$confirm('确定要取消？', '提示', { type: 'warning' }).catch(() => {})
            if(confirm) {
                const res = await this.$http({
                    url: '/mall/omsorder/cancelOrder',
                    method: 'GET',
                    params: {id: row.id}
                })
                if (this.ResultMessage(res)) {
                    this.getDataList()
                }
            }
        },

        /**
         * 物流跟踪窗口
         */
        handleLogisticsVisible(row) {
            this.logistics.dialogVisible = true
            this.$refs.logistics.getDeliveryResult(row.deliverySn)
        },

        /**
         * 订单备注窗口
         */
        handleRemarksOrderVisible(row) {
            this.remarksOrder.id = row.id
            this.remarksOrder.remarks = row.remarks
            this.remarksOrder.dialogVisible = true
        },
        /**
         * 订单备注
         */
        async handleRemarks() {
            const res = await this.$http({
                url: '/mall/omsorder/remarks',
                method: 'POST',
                data: this.remarksOrder
            })
            if (this.ResultMessage(res)) {
                this.remarksOrder.dialogVisible = false
                this.getDataList()
            }
        },

        /**
         * 订单发货窗口
         */
        handleInnerDeliveryVisible(row) {
            this.order = row
            this.deliveryOrder.id = this.order.id
            this.getDeliveryCompany()
            this.deliveryOrder.dialogVisible = true
        },

        /**
         * 快递公司
         */
        async getDeliveryCompany() {
            const res = await this.$http({
                url: '/mall/mallexpresscompany/list',
                method: 'GET'
            })
            this.companyOptions = Object.assign({}, res.data)
        },

        /**
         * 订单发货
         */
        async handleExpressDelivery() {
            const refs = this.$refs
            this.submitLoading = true
            let valid = await refs['deliveryOrder'].validate().catch(() => {})
            if(this.deliveryOrder.deliverType == 1) {
                valid = true
            }
            if(valid) {
                const res = await this.$http({
                    url: '/mall/omsorder/expressDelivery',
                    method: 'POST',
                    data: this.deliveryOrder
                })
                if (this.ResultMessage(res)) {
                    this.getDataList()
                    this.deliveryOrder.dialogVisible = false
                }
            } else {
                this.submitLoading = false
            }
        },

        /**
         * 确认收货
         */
        async handleConfirmReceivePack(row) {
            const confirm = await this.$confirm('确认收货？', '提示', { type: 'warning' }).catch(() => {})
            if(confirm) {
                const res = await this.$http({
                    url: '/mall/omsorder/confirmReceivePack',
                    method: 'GET',
                    params: {id: row.id}
                })
                if (this.ResultMessage(res)) {
                    this.getDataList()
                }
            }
        },

        /**
         * el-dropdown 传入多参数
         */
        beforeHandleCommand(index, row, name){
            return { 'index': index, 'row': row, 'name': name }
        },
        /**
         * el-dropdown 更多操作
         */
        async handleCommand(command) {
            const { name, row } = command
            if (name === 'remarks') {
                this.handleRemarksOrderVisible(row)
            } else if(name === 'logistics') {
                this.handleLogisticsVisible(row)
            } else if(name === 'deleted') {
                this.handleDelete(row)
            }
        },

        handleChangeDateAttr() {
            this.dateRange = null
            this.searchForm.dateRange = null
            this.getDataList()
        },
        handleChangeStatus() {
            this.getDataList()
        },

        /**
         * 搜索
         */
        handleSearch() {
            this.getDataList()
        },
        /**
         * 重新加载数据表格
         */
        handleReload() {
            this.getDataList()
        },
        /**
         * 重置搜索表单
         */
        handleReset() {
            this.dateRange = null
            this.searchForm.dateRange = null
            this.$refs.searchForm1.resetFields()
            this.$refs.searchForm2.resetFields()
            this.getDataList()
        },

        /**
         * 下载导出数据
         */
        async handleExport() {
            const notify = this.$notify({ title: '提示', message: '正在下载，请稍等。', type: 'success', duration: 0 });
            const data = await this.$http({
                url: '/mall/omsorder/export',
                method: 'POST',
                responseType: 'blob',
                data: {},
            }).catch(err => {console.log(err)})

            if (!data) { return }
            let url = window.URL.createObjectURL(new Blob([data]));
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', data.filename);

            document.body.appendChild(link);
            link.click()
            setTimeout(() => { notify.close() }, 1000)
        },

    },

    filters: {
        formatOrderType(value) {
            if (value === 0) {
                return '普通订单';
            } else if (value === 1) {
                return '活动订单';
            } else if (value === 2) {
                return '拼团订单';
            } else if (value === 3) {
                return '秒杀订单';
            } else if (value === 4) {
                return '砍价订单';
            } else if (value === 5) {
                return '核销订单';
            } else {
                return '-';
            }
        },
        formatStatus(value) {
            if (value === 0) {
                return '待付款';
            } else if (value === 1) {
                return '待发货';
            } else if (value === 2) {
                return '已发货';
            } else if (value === 3) {
                return '已完成';
            } else if (value === 4) {
                return '已关闭';
            } else {
                return '-';
            }
        },
        formatIsPay(value) {
            if (value === 0) {
                return '未支付';
            } else if (value === 1) {
                return '已支付';
            } else {
                return '-';
            }
        },
        formatDeliverType(value) {
            if (value === 0) {
                return '送货上门';
            } else if (value === 1) {
                return '到店自提';
            } else {
                return '-';
            }
        },
        formatPayType(value) {
            if (value === 0) {
                return '支付宝';
            } else if (value === 1) {
                return '微信';
            } else if (value === 2) {
                return '银联';
            } else if (value === 3) {
                return '货到付款';
            } else {
                return '-';
            }
        },
        formatSourceType(value) {
            if (value === 0) {
                return 'PC订单';
            } else if (value === 1) {
                return '微信订单';
            } else if (value === 2) {
                return 'APP订单';
            } else {
                return '-';
            }
        }
    }

}
</script>

<style lang="scss" scoped>
@import '../../../assets/styles/mixin.scss';
.wrap{
    .payAmount{
        color: red;
    }
}
.skus_wrap{
    display: flex;
    padding: 10px 0;

    .sku_img{
        display: flex;
        justify-content: center;
        align-items: center;
        flex: 1;
    }
    .sku_name{
        display: flex;
        align-items: center;
        flex: 3;
        width: 100px;
        height: 70px;
        @include textoverflow(3);
    }
    .sku_amount{
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: flex-start;
        flex: 1;
        align-items: center;
        span{
            display: block;
        }
    }

    &:first-child{
        padding: 0 0;
    }
    &:last-child{
        border: 0;
        padding: 0 0;
    }
}
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 12px;
    margin-left: 10px;
}
.el-icon-arrow-down {
    font-size: 12px;
}

.dialog_centent_wrap{
    height: 500px;
    overflow-y: auto;
    padding: 0 10px;
}
.divider{
    border-bottom: 1px solid #EBEEF5;
    margin-bottom: 10px;
    padding-bottom: 5px;
    font-size: 16px;
    font-weight: 500;
    .title{
        margin-left: 10px;
    }
}
.detail_wrap{

    .table_layout {
        margin-bottom: 20px;
        border-left: 1px solid #dcdfe6;
        border-top: 1px solid #dcdfe6;
    }

    .table_cell {
        height: 60px;
        border-right: 1px solid #dcdfe6;
        border-bottom: 1px solid #dcdfe6;
        padding: 10px;
        font-size: 14px;
        color: #606266;
        text-align: center;
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .table_cell_title {
        border-right: 1px solid #dcdfe6;
        border-bottom: 1px solid #dcdfe6;
        padding: 10px;
        background: #f2f6fc;
        text-align: center;
        font-size: 14px;
        color: #303133;
    }

    .total_wrap{
        display: flex;
        flex-direction: column;
        border-top: 1px dashed #ccc;
        margin-top: 10px;
        padding-top: 5px;
        align-items: flex-end;
        .wrap{
            div{
                line-height: 1.5;
                width: 200px;
                display: flex;
                span:first-child{
                    display: flex;
                    min-width: 70px;
                }
                span:last-child{
                    display: block;
                }
                .amount_red{
                    color: red
                }
            }
        }
    }
}

.action{
    display: flex;
    justify-content: flex-end;
}
</style>
